import 'package:dio/dio.dart';
import 'package:provider/provider.dart';
import 'package:flutter_lagou/provider/UserProvider.dart';
import '../utils/Global.dart';
Dio? initDio() {
  BaseOptions _baseOptions = BaseOptions(
    baseUrl: 'http://192.168.2.135:3000',
    // baseUrl: 'http://eduboss.lagou.com',
    connectTimeout: const Duration(seconds: 5)
  );
  Dio dio = Dio(_baseOptions);

  // 添加拦截器
  dio.interceptors.add(
    InterceptorsWrapper(
      // 请求拦截
      onRequest:(RequestOptions options, handler) {
        // 将token封装到header中 ?.read<UserProvider>().user
        var user = G.getCurrentContext()?.read<UserProvider>().user;
        if(user!.isNotEmpty) {
          options.headers['Authorization'] = user['access_token']; 
        }
        print('${user} getCurrentContext');
        return handler.next(options); //continue
      },
      onResponse: (Response response, handler) {
        if(response?.data == null || response.data['state'] != 1) {
          response.data = null;
        } 
        
        return handler.next(response); // continue
       
      },
      onError: <DioException> (DioException  error, handler) {
        return error;
      },
    )
  );

  // 返回dio
  return dio;
}

